<template>
  <Form
    :validation-schema="mySchema"
    v-slot="{ errors }"
    class="xtx-form"
    autocomplete="off"
    ref="formCom"
  >
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-user"></i>
        <Field
          :class="{ err: errors.account }"
          v-model="form.account"
          name="account"
          class="input"
          type="text"
          placeholder="请输入用户名"
        />
      </div>
      <div v-if="errors.account" class="error">{{ errors.account }}</div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-phone"></i>
        <Field
          v-model="form.mobile"
          name="mobile"
          class="input"
          type="text"
          :class="{ err: errors.mobile }"
          placeholder="请输入手机号"
        />
      </div>
      <div v-if="errors.mobile" class="error">
        {{ errors.mobile }}
      </div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-code"></i>
        <Field
          v-model="form.code"
          name="code"
          class="input"
          type="text"
          placeholder="请输入验证码"
          :class="{ err: errors.code }"
        />
        <span class="code" @click="send">
          {{ time === 0 ? "发送验证码" : `${time}秒后重发` }}
        </span>
      </div>
      <div v-if="errors.code" class="error">
        {{ errors.code }}
      </div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-lock"></i>
        <Field
          v-model="form.password"
          name="password"
          class="input"
          type="password"
          placeholder="请输入密码"
          :class="{ err: errors.password }"
        />
      </div>
      <div v-if="errors.password" class="error">
        {{ errors.password }}
      </div>
    </div>
    <div class="xtx-form-item">
      <div class="field">
        <i class="icon iconfont icon-lock"></i>
        <Field
          v-model="form.rePassword"
          name="rePassword"
          class="input"
          type="password"
          placeholder="请确认密码"
          :class="{ err: errors.rePassword }"
        />
      </div>
      <div v-if="errors.rePassword" class="error">
        {{ errors.rePassword }}
      </div>
    </div>
    <a href="javascript:;" class="submit" @click="submit">立即提交</a>
  </Form>
</template>

<script>
import { Form, Field } from 'vee-validate'
import { reactive } from 'vue-demi'
import schema from '@/utils/vee-validate-schema'
import { userQQPatchCode, userQQPatchLogin } from '@/api/user'
import { ref, onUnmounted } from 'vue'
import Message from '@/components/library/Message'
import { useIntervalFn } from '@vueuse/core'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
export default {
  name: 'CallbackPatch',
  components: { Form, Field },
  props: {
    unionId: {
      type: String,
      default: ''
    }
  },
  setup (props) {
    // 1.表单校验 多两种校验规则 用户名是否存在 再次输入密码是否一致
    // 2.发送短信验证码 发送的接口api不一样
    // 3.完善信息

    // 表单数据对象
    const form = reactive({
      mobile: null,
      code: null,
      account: null,
      password: null,
      rePassword: null
    })
    // 表单校验规则
    const mySchema = {
      mobile: schema.mobile,
      code: schema.code,
      account: schema.accountApi,
      password: schema.password,
      rePassword: schema.rePassword
    }

    // -----------------------------
    // 发短信的代码
    // 发送短信验证码
    // start 开启 stop 停止
    // 回调函数 执行间隔 是否立即开启
    // 1.发送验证码
    // 1.1绑定发送验证码点击事件
    // 1.2校验手机号 成功发送短信(定义api) 请求成功开启60秒倒计时 不能再次点击 结束 恢复原样
    // 1.3 校验失败 校验样式显示出来
    const time = ref(0)
    const formCom = ref(null)
    const { pause, resume } = useIntervalFn(() => {
      time.value--
      if (time.value <= 0) {
        pause()
      }
    }, 1000, false)

    onUnmounted(() => {
      pause()
    })
    // 发送短信
    const send = async () => {
      const valid = schema.mobile(form.mobile)
      if (valid === true) {
        // 通过
        if (time.value === 0) {
          // 没有倒计时 才可以发送请求
          await userQQPatchCode(form.mobile)
          Message({ type: 'success', text: '发送成功' })
          time.value = 60
          resume()
        }
      } else {
        // 未通过 触发vee的错误函数 显示错误信息
        // setFieldError(字段,错误信息)
        formCom.value.setFieldError('mobile', valid)
      }
    }

    // --------------------------------------------------------立即提交
    const store = useStore()
    const router = useRouter()
    const submit = async () => {
      // console.log(1)
      const valid = await formCom.value.validate()
      console.log(valid)
      // console.log(2)
      if (valid) {
        // 校验成功 发送请求
        // console.log(1)

        userQQPatchLogin({ unionId: props.unionId, ...form }).then(data => {
          // 实现和之前登录一样的逻辑
          // 存储用户信息
          const { id, account, avatar, mobile, nickname, token } = data.result
          store.commit('user/setUser', { id, account, avatar, mobile, nickname, token })

          store.dispatch('cart/mergeLocalCart').then(() => {
            // 跳转 来源也或首页
            router.push(store.state.user.redirectUrl || '/')
            // 消息提示
            Message({ type: 'success', text: 'QQ完善信息成功' })
          })
        }).catch(e => {
          Message({ type: 'error', text: '完善信息失败' })
        })
      }
    }
    return { form, mySchema, send, formCom, time, submit }
  }
}
</script>

<style scoped lang='less'>
.code {
  position: absolute;
  right: 0;
  top: 0;
  line-height: 50px;
  width: 80px;
  color: #999;
  &:hover {
    cursor: pointer;
  }
}
</style>
